package com.linck.im.dao;

import com.linck.im.dao.mapper.AccountMapper;
import com.linck.im.model.entity.Account;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 * sql连接工具
 *
 * @author: linck
 * @create: 2021-01-22
 */
@Slf4j
public class SqlSessionFactoryUtil {

    public static final SqlSessionFactory sqlSessionFactory;

    //public static final ThreadLocal<SqlSession> session = new ThreadLocal<>();

    static {
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    public static SqlSession getSqlSession() {
        /*SqlSession sqlSession = session.get();
        if (sqlSession == null) {
            sqlSession = sqlSessionFactory.openSession();
            session.set(sqlSession);
        }*/
        return sqlSessionFactory.openSession();
    }

    @Test
    public void test() {
        try (SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSession();) {
            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
            Account test = mapper.selectAccount("test");
            System.out.println(test);
        }
    }

}
